package com.smsc.headend.task.engine.executor.impl.ansi;

import com.smsc.headend.module.asset.dmo.ComConfigDMO;
import com.smsc.headend.module.asset.entity.Meter;
import com.smsc.headend.module.data.dmo.DeviceSAPandKeys;
import com.smsc.headend.module.data.dto.AnsiSubDataItemDTO;
import com.smsc.headend.module.protocol.cosem.util.ByteUtils;
import com.smsc.headend.module.task.dto.AtomicTask;
import com.smsc.headend.module.task.dto.AtomicTaskState;
import com.smsc.headend.module.task.dto.Task;
import com.smsc.headend.task.engine.dao.TaskDAO;
import com.smsc.headend.task.engine.exception.UDISTaskExecutorException;
import com.smsc.headend.task.engine.executor.TaskExecutor;
import com.smsc.headend.task.engine.handler.impl.ansi.GetTouSeasonHandler;
import com.smsc.headend.task.engine.service.ConnectorService;
import com.smsc.headend.task.engine.service.FeignAssetManagementService;
import com.smsc.headend.task.engine.service.asset.AssetService;
import com.smsc.headend.task.engine.service.task.TaskPacketService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;

@Slf4j
public class GetTouSeasonExecutor implements TaskExecutor {
    @Autowired
    TaskPacketService packetService;
    @Autowired
    ConnectorService connectorService;
    @Autowired
    FeignAssetManagementService assetManagementRemoteService;
    @Autowired
    TaskDAO taskDAO;
    @Autowired
    AssetService assetService;

    @Override
    public AtomicTaskState execute(Task task, AtomicTask atomicTask) throws UDISTaskExecutorException {
        Meter meter = getMeter(task, assetService);
        ComConfigDMO comConfigDMO = assetManagementRemoteService.getComConfigById(task.getComId());
        AnsiSubDataItemDTO dataItemDTO = new AnsiSubDataItemDTO();
        dataItemDTO.setTableId(54);
        DeviceSAPandKeys deviceKeys = assetManagementRemoteService.getMeterCommunicationKey(meter.getMeterId(), 2);
        AtomicTaskState atomicState = taskDAO.hashGetAtomicTaskState(atomicTask.getAtomicTaskNo());
        if (atomicState == null) {
            atomicState = createAtomicState(GetTouSeasonHandler.class);
            atomicState.setBlockNumber(0);
        }

        int count = 16 * 3;
        dataItemDTO.setTableOffset(24 + atomicState.getBlockNumber() * count);
        dataItemDTO.setByteCount(count);
        byte[] packets = packetService.buildReadOneAttributePacket(dataItemDTO, comConfigDMO, deviceKeys);
        log.debug(ByteUtils.byteToHexString(packets));
        connectorService.sendPacket(task, atomicTask, 2, task.getIsODR(), packets);

        return atomicState;
    }

    @Override
    public Boolean handleFailure(Task task, AtomicTask atomicTask, String message) {
        log.info("error {}, ", message);
        // key 回曲线的dataItemId给web
        taskDAO.addTaskData(task.getTaskNo(), atomicTask.getAtomicTaskNo(), "Execute Get Tou Season", message, 3600l, false);

        return true;
    }
}
